﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Elmah;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class UsersController : BaseController
    {
        [HttpGet]
        [ActionName("get_all_users")]
        public JsonResult GetAll(string roleName, int pageIndex = 0, int pageSize = 0)
        {
            //có phân trang
            try
            {
                var lstUser = new List<UserModel>();
                if (pageSize > 0 && pageIndex >= 0)
                {
                    var list = unitOfWork.UserRepository.GetWithPaging(pageIndex, pageSize);
                    lstUser.AddRange(from item in list
                                     let user = Membership.GetUser(item.UserName)
                                     let profile = ProfileHelpers.GetUserProfile(item.UserName)
                                     where user != null
                                     && (roleName == "" || Roles.IsUserInRole(user.UserName, roleName))
                                     select new UserModel()
                                                {
                                                    UserName = user.UserName,
                                                    IsApproved = user.IsApproved,
                                                    Address = profile.Address,
                                                    Email = user.Email,
                                                    RoleName = string.Join(", ", Roles.GetRolesForUser(user.UserName)),
                                                    RoleDisplayName = unitOfWork.RoleRepository.GetRoleDisplayName(Roles.GetRolesForUser(user.UserName)),
                                                    FullName = profile.FullName,
                                                    Gender = profile.Gender,
                                                    Mobile = profile.Mobile,
                                                    Telephone = profile.Telephone
                                                });
                    return Json(new JsonResponse()
                    {
                        Status = true,
                        Result = new
                        {
                            PageIndex = list.PageIndex,
                            PageSize = list.PageSize,
                            PageCount = list.PageCount,
                            List = lstUser
                        }
                    }, JsonRequestBehavior.AllowGet);
                }
                //không phân trang
                else
                {

                    var list = unitOfWork.UserRepository.Get();
                    lstUser.AddRange(from item in list
                                     let user = Membership.GetUser(item.UserName)
                                     let profile = ProfileHelpers.GetUserProfile(item.UserName)
                                     where user != null
                                     select new UserModel()
                                     {
                                         UserName = user.UserName,
                                         IsApproved = user.IsApproved,
                                         Address = profile.Address,
                                         Email = user.Email,
                                         FullName = profile.FullName,
                                         Gender = profile.Gender,
                                         Mobile = profile.Mobile,
                                         Telephone = profile.Telephone
                                     });

                    return Json(new JsonResponse() { Status = true, Result = lstUser }, JsonRequestBehavior.AllowGet);
                } //end if
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(new NotSupportedException("", ex));
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                throw;
            }//end try
        }

        [HttpGet]
        [ActionName("search_user")]
        public JsonResult Search(string key)
        {
            try
            {
                var list = unitOfWork.UserRepository.Search(key);
                var lstUser = new List<UserModel>();
                lstUser.AddRange(from item in list
                                 let user = Membership.GetUser(item.UserName)
                                 let profile = ProfileHelpers.GetUserProfile(item.UserName)
                                 where user != null
                                 select new UserModel()
                                 {
                                     UserName = user.UserName,
                                     IsApproved = user.IsApproved,
                                     Address = profile.Address,
                                     Email = user.Email,
                                     FullName = profile.FullName,
                                     Gender = profile.Gender,
                                     Mobile = profile.Mobile,
                                     Telephone = profile.Telephone
                                 });
                return Json(new JsonResponse() { Status = true, Result = lstUser },
                            JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                //throw;
            }
        }

        [HttpGet]
        [ActionName("get_roles")]
        public JsonResult GetRoles(string userName)
        {
            string[] existsRole = Roles.GetRolesForUser(userName);
            var allRole = Roles.GetAllRoles();
            var uiModel = allRole.Select(roleItem => new UserInRoleModel()
                                                         {
                                                             UserName = userName,
                                                             RoleName = roleItem,
                                                             IsInRole = existsRole.Contains(roleItem)
                                                         }).ToList();
            return Json(
                new JsonResponse()
                    {
                        Status = true,
                        Result = uiModel
                    }
                , JsonRequestBehavior.AllowGet);
        }
        [HttpPut]
        [ActionName("assign_role")]
        public JsonResult AssignRole(UserInRoleModel model)
        {
            if (Membership.GetUser(model.UserName) != null && Roles.RoleExists(model.RoleName))
            {
                if (model.IsInRole)
                {
                    Roles.AddUserToRole(model.UserName, model.RoleName);
                }
                else
                {
                    Roles.RemoveUserFromRole(model.UserName, model.RoleName);
                }
                return Json(SimplyResponse.Response200());
            }
            return Json(SimplyResponse.Response500());
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult GetList(string id, string userName)
        {
            if (!string.IsNullOrWhiteSpace(userName))
            {
                MembershipUser mbuser = Membership.GetUser(userName);
                if (mbuser != null)
                {
                    ProfileHelpers profile = ProfileHelpers.GetUserProfile(mbuser.UserName);
                    var umodel = new UserModel()
                    {
                        UserName = mbuser.UserName,
                        Address = profile.Address,
                        Email = mbuser.Email,
                        FullName = profile.FullName,
                        Gender = profile.Gender,
                        Mobile = profile.Mobile,
                        Telephone = profile.Telephone
                    };
                    return Json(umodel, JsonRequestBehavior.AllowGet);
                }
            }
            var lstUser = new List<UserModel>();
            foreach (var useritem in Membership.GetAllUsers())
            {
                var user = (MembershipUser)useritem;
                ProfileHelpers profile = ProfileHelpers.GetUserProfile(user.UserName);
                var isAdd = false;
                if (!string.IsNullOrWhiteSpace(id))
                {
                    string[] userList = Roles.GetUsersInRole(id);
                    isAdd = userList.Contains(user.UserName);
                }
                isAdd = isAdd || string.IsNullOrWhiteSpace(id);
                if (isAdd)
                    lstUser.Add(new UserModel()
                    {
                        UserName = user.UserName,
                        Address = profile.Address,
                        Email = user.Email,
                        FullName = profile.FullName,
                        Gender = profile.Gender,
                        Mobile = profile.Mobile,
                        Telephone = profile.Telephone
                    });
            }
            return Json(lstUser, JsonRequestBehavior.AllowGet);
        }
        // Update Role
        [HttpPut]
        [ActionName("update_user")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateUser(UserModel userModel, string modifyscope = "all")
        {
            MembershipUser user = Membership.GetUser(userModel.UserName);
            if (user != null)
            {
                if (modifyscope.ToUpper() == "ISAPPROVED")
                {
                    user.IsApproved = userModel.IsApproved;
                }
                else
                {
                    user.Email = userModel.Email;
                    var profile = ProfileHelpers.GetUserProfile(userModel.UserName);
                    profile.Address = userModel.Address;
                    profile.FullName = userModel.FullName;
                    profile.FirstName = userModel.FullName.GetFirstName();
                    profile.LastName = userModel.FullName.GetLastName();
                    profile.Gender = userModel.Gender;
                    profile.Mobile = userModel.Mobile;
                    profile.Telephone = userModel.Telephone;
                    profile.Save();
                }
                Membership.UpdateUser(user);
            }
            return Json(SimplyResponse.Response200());
        }
        [HttpPost]
        [ActionName("create_user")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult CreateUser(UserModel userModel, string roleName)
        {
            try
            {
                Membership.CreateUser(userModel.UserName, userModel.Password, userModel.Email);
                var profile = ProfileHelpers.GetUserProfile(userModel.UserName);
                profile.Address = userModel.Address;
                profile.FullName = userModel.FullName;
                profile.FirstName = userModel.FullName.GetFirstName();
                profile.LastName = userModel.FullName.GetLastName();
                profile.Gender = userModel.Gender;
                profile.Mobile = userModel.Mobile;
                profile.Telephone = userModel.Telephone;
                profile.Save();
                Roles.AddUserToRole(userModel.UserName, roleName);
                return Json(SimplyResponse.ResposeWithId(userModel.UserName));
            }
            catch
            {
                return Json(SimplyResponse.Response500());
            }
        }
        //Delete User
        [HttpPost]
        [ActionName("delete_user")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteUser(string id)
        {
            if (Membership.GetUser(id) != null && Membership.GetUser() != Membership.GetUser(id))
            {
                Membership.DeleteUser(id, true);
            }
            return Json(SimplyResponse.Response200());
        }

        /// <summary>
        /// Lấy toàn bộ người dùng theo phòng ban
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("get_users_by_dept")]
        public JsonResult GetUsersByDept(int deptId)
        {
            try
            {
                var items = unitOfWork.UserRepository.GetByDeptId(deptId).Select(o => new UserModel(o)).ToList();
                return Json(new JsonResponse()
                    {
                        Status = true,
                        Result = items
                    }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                throw;
            }
        }

        [HttpPost]
        [ActionName("get_role_list")]
        public JsonResult GetRoleList()
        {
            var roleList = new RoleTree
                               {
                                   attr = new RoleTreeAttribute { id = "" },
                                   id = "",
                                   data = "Danh sách vai trò",
                                   children = new List<RoleTree>()
                               };
            foreach (var role in unitOfWork.RoleRepository.Get())
            {
                var newRoot = new RoleTree { attr = new RoleTreeAttribute(), id = role.RoleName, data = role.RoleDisplayName };
                newRoot.attr.id = role.RoleName;
                newRoot.attr.selected = true;
                roleList.children.Add(newRoot);
            }
            return Json(roleList);
        }
    }
}
